package com.hemaapp.yjnh.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.OrderDetail;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;

/**
 * 预约订单详情
 *
 * @author GuiyouZhang
 */
public class BookOrderDetailActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_buycode)
    TextView tvBuycode;
    @Bind(R.id.tv_client_info)
    TextView tvClientInfo;
    @Bind(R.id.tv_order_sn_1)
    TextView tvOrderSn1;
    @Bind(R.id.layout_goods)
    LinearLayout layoutGoods;
    @Bind(R.id.tv_date_start)
    TextView tvDateStart;
    @Bind(R.id.tv_date_end)
    TextView tvDateEnd;
    @Bind(R.id.tv_cash_stamp)
    TextView tvCashStamp;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_order_sn_2)
    TextView tvOrderSn2;
    @Bind(R.id.tv_order_time)
    TextView tvOrderTime;
    @Bind(R.id.tv_order_status)
    TextView tvOrderStatus;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.tv_delete)
    TextView tvDelete;
    @Bind(R.id.tv_comment)
    TextView tvComment;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;
    private OrderDetail mOrder;//当前的订单
    private User user;
    private HemaButtonDialog hbDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_book_order_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        String order_id = mIntent.getStringExtra("order_id");
        getNetWorker().getOrderDetail(user.getToken(), order_id);
    }

    @Override
    protected void setListener() {
        titleText.setText("预约详情");
        titleRightBtn.setVisibility(View.GONE);
    }

    private void setData() {
        tvBuycode.setText("消费码："+mOrder.getCostcode());
        tvClientInfo.setText("联系人："+mOrder.getConsignee()+"    "+mOrder.getPhone());
        tvOrderSn1.setText("订单号："+mOrder.getBill_sn());
        tvOrderSn2.setText("订单号："+mOrder.getBill_sn());
        tvOrderTime.setText("下单时间："+mOrder.getRegdate());
        tvTotalFee.setText("¥"+ uuUtils.formatAfterDot2(mOrder.getTotal_fee()));
        double totalFee = 0.0;
        double stampFee = 0.0;
        try {
            totalFee = Double.parseDouble(mOrder.getTotal_fee());
            stampFee = Double.parseDouble(mOrder.getScore_fee());
        }catch (Exception e) {
            e.printStackTrace();
        }
        tvCashStamp.setText("¥"+ uuUtils.formatAfterDot2(totalFee-stampFee+"")+" + ");
        BaseUtil.addStampSign(mContext, tvCashStamp, R.drawable.food_stamp_grey);
        tvCashStamp.append(uuUtils.formatAfterDot2(mOrder.getScore_fee())+"粮票");
        setTradeStatus();
        //计算起始时间和结束时间
        String start = mOrder.getStartdate();
        tvDateStart.setText(mOrder.getStartdate());
        String days = mOrder.getChildItems().get(0).getDays();
        try{
            if (days != null && days.length()>0) {
                int day = Integer.parseInt(days);
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
                Date date =sdf.parse(start);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, day);
                tvDateEnd.setText(sdf.format(calendar.getTime()));
            }else {
                tvDateEnd.setText(start);
            }
        }catch (Exception e) {
            e.printStackTrace();
            tvDateEnd.setText(start);
        }
        //动态添加多个商品
        if (layoutGoods.getChildCount() != 0) {
            layoutGoods.removeAllViews();
        }
        for (int i = 0; i < mOrder.getChildItems().size(); i++) {
            OrderDetail.ChildItemsBean child = mOrder.getChildItems().get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_goods, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            setItem(i, child, view, ivHolder);
            view.setTag(mOrder.getChildItems().get(i));
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    OrderDetail.ChildItemsBean child = (OrderDetail.ChildItemsBean) v.getTag();
                    // 先根据商品属性自己判断
                    Intent intent = BaseUtil.createBlogIntent(mContext, child.getType());
                    intent.putExtra("blog_id", child.getBlog_id());
                    mContext.startActivity(intent);
                }
            });
        }
    }

    private void setTradeStatus() {
        String status = "";
        if (mOrder.getStatetype().equals("2")) {//订单状态	1：有效 2：已删除
            tvOrderStatus.setText("订单状态：交易关闭");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
            return;
        }
        //		交易状态	2 待消费 3 待评价 4 交易成功
        if (mOrder.getTradetype().equals("2")) {
            String returnflag = mOrder.getReturnflag();//退货状态	0：无 非0：有
            if (returnflag.equals("0")) {//没有申请退款
                tvOrderStatus.setText("订单状态：待消费");
                setBottomButton(new int[]{View.VISIBLE, View.VISIBLE, View.GONE, View.GONE});
            } else {
                tvOrderStatus.setText("订单状态：交易关闭");
                setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
            }
        } else if (mOrder.getTradetype().equals("3")) {
            tvOrderStatus.setText("订单状态：待评价");
            setBottomButton(new int[]{View.VISIBLE, View.GONE, View.GONE, View.VISIBLE});
        } else if (mOrder.getTradetype().equals("4")) {
            tvOrderStatus.setText("订单状态：交易成功");
            setBottomButton(new int[]{View.VISIBLE, View.GONE, View.VISIBLE, View.GONE});
        } else if (mOrder.getTradetype().equals("0")) {
            tvOrderStatus.setText("订单状态：未付款");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        } else if (mOrder.getTradetype().equals("1")) {
            tvOrderStatus.setText("订单状态：等待商家确认");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }
    }

    /**
     * @param visibility
     * 依次为：取消订单、删除订单、评价
     */
    public void setBottomButton(int[] visibility) {
        layoutBottom.setVisibility(visibility[0]);
        if (visibility[0] == View.VISIBLE) {
            tvCancel.setVisibility(visibility[1]);
            tvDelete.setVisibility(visibility[2]);
            tvComment.setVisibility(visibility[3]);
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                String opera = netTask.getParams().get("keytype");
                if (opera.equals("1"))
                    XtomToastUtil.showShortToast(mContext, "删除成功");
                else if(opera.equals("3"))
                    XtomToastUtil.showShortToast(mContext, "取消成功");
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case ORDER_GET:
                HemaArrayResult<OrderDetail> bResult = (HemaArrayResult<OrderDetail>) baseResult;
                mOrder = bResult.getObjects().get(0);
                setData();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask, HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                String opera = netTask.getParams().get("keytype");
                if (opera.equals("1"))
                    XtomToastUtil.showShortToast(mContext, "删除失败，"+baseResult.getMsg());
                else if(opera.equals("3"))
                    XtomToastUtil.showShortToast(mContext, "取消失败，"+baseResult.getMsg());
                break;
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取订单失败," + baseResult.getMsg());
                finish();
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                String opera = netTask.getParams().get("keytype");
                if (opera.equals("1"))
                    XtomToastUtil.showShortToast(mContext, "删除失败, 请稍后再试");
                else if(opera.equals("3"))
                    XtomToastUtil.showShortToast(mContext, "取消失败, 请稍后再试");
                break;
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取订单失败, 请稍后再试");
                finish();
                break;
        }
    }


    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.UPDATE_ORDER) {
            getNetWorker().getOrderDetail(user.getToken(), mOrder.getId());
        }
    }

    @OnClick({R.id.title_left_btn, R.id.tv_cancel, R.id.tv_delete, R.id.tv_comment})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_cancel:
                cancelOrder();
                break;
            case R.id.tv_delete:
                HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                hbDialog.setText("确认删除订单吗？");
                hbDialog.setLeftButtonText("取消");
                hbDialog.setRightButtonText("确定");
                hbDialog.setRightButtonTextColor(getResources().getColor(
                        R.color.theme_orange));
                hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        getNetWorker().orderSaveoperate(user.getToken(),
                                mOrder.getId(), "1", "无", "无", "无", "无");
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_comment:
                Intent itCommit = new Intent(mContext, CommentProductionActivity.class);
                itCommit.putExtra("goods_id", mOrder.getChildItems().get(0).getId());
                startActivity(itCommit);
                break;
        }
    }
    /**
     * 取消预约，也就是申请退款
     */
    public void cancelOrder() {
        String enable = mOrder.getReturn_enable();
        // 预约订单是否能退款 0否；1是
        if (enable.equals("1")) {
            HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
            hbDialog.setText("确认取消预约吗？");
            hbDialog.setLeftButtonText("取消");
            hbDialog.setRightButtonText("确定");
            hbDialog.setRightButtonTextColor(getResources().getColor(
                    R.color.theme_orange));
            hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                @Override
                public void onRightButtonClick(HemaButtonDialog dialog) {
                    dialog.cancel();
                    getNetWorker().orderSaveoperate(user.getToken(),
                            mOrder.getChildItems().get(0).getId(), "3", "无", "无", "无", "无");
                }

                @Override
                public void onLeftButtonClick(HemaButtonDialog dialog) {
                    dialog.cancel();
                }
            });
        } else {
            Dialog dialog2 = new Dialog(mContext, R.style.dialog);
            View view = getLayoutInflater().inflate(
                    R.layout.dialog_refuse_aftersale, null);
            TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
            final String number = getApplicationContext().getSysInitInfo()
                    .getSys_service_phone();
            tv_phone.setText(number);
            tv_phone.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri
                            .parse("tel:" + number));
                    startActivity(intent);
                }
            });
            dialog2.setCancelable(true);
            dialog2.setContentView(view);
            dialog2.show();
        }
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        TextView tvCommit;
        TextView tvAfterSale;
        TextView tvHint;
        View div;
    }

    /**一个订单中的多个商品
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.img);
        ivHolder.name = (TextView) view.findViewById(R.id.good_name);
        ivHolder.price = (TextView) view.findViewById(R.id.price);
        ivHolder.amount = (TextView) view.findViewById(R.id.count);
        ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
        ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
        ivHolder.tvHint = (TextView) view.findViewById(R.id.tv_hint);
        ivHolder.div = view.findViewById(R.id.divider);
    }

    private void setItem(int i, final OrderDetail.ChildItemsBean child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText("¥"+uuUtils.formatAfterDot2(child.getPrice()));
        ivHolder.amount.setText("x" + child.getBuycount());

        if (i == mOrder.getChildItems().size()-1) {
            ivHolder.div.setVisibility(View.GONE);
        }else {
            ivHolder.div.setVisibility(View.VISIBLE);
        }
        ivHolder.tvCommit.setVisibility(View.GONE);
        ivHolder.tvAfterSale.setVisibility(View.GONE);
        layoutGoods.addView(view);
    }
}
